package four;
import java.util.*;
public class A071 {


    //347.前k个高频单词
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int x:nums) {
            map.put(x,map.getOrDefault(x,0)+1);
        }
        PriorityQueue<int[]> queue = new PriorityQueue<>(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[1] - o2[1];
            }
        });
        //遍历，小根堆
        for(Map.Entry<Integer,Integer> t:map.entrySet()) { //遍历Map
            int key = t.getKey(), value = t.getValue();
            if(queue.size()<k) {
                queue.add(new int[]{key,value});
            }else {
                int[] min = queue.peek();
                if(min[1] < value) {
                    queue.poll();
                    queue.add(new int[]{key,value});
                }
            }
        }
        //收集结果
        int[] ret = new int[k];
        int i=0;
        while (!queue.isEmpty()) {
            ret[i]=queue.poll()[0];
            i++;
        }
        return ret;
    }
}
